using AgCIM.Tools.DBLink;
using AutoUpdaterDotNET;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Data;
using System.Reflection;
using System.Text;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace DailyLog
{
    public partial class Form1 : Form
    {
        private ConnectionDatabase_S2 m_connection { get; set; }
        private string m_tableName { get; set; } = "agcim_departmentmanage_dailylog";

        public Form1()
        {
            InitializeComponent();

            this.Text = "AgCIM  技术日志编写软件 -" + Assembly.GetExecutingAssembly().GetName().Version;

            CheckUpdate();

            this.dataGridView1.CellPainting += dataGridView1_CellPainting;
            this.dataGridView1.CellMouseClick += dataGridView1_CellMouseClick;
            this.dataGridView1.CellDoubleClick += dataGridView1_CellDoubleClick;
            // 为搜索文本框添加回车事件
            this.textBox_search.KeyDown += (s, e) =>
            {
                if (e.KeyCode == Keys.Enter)
                {
                    QuerySomeDays();
                    e.SuppressKeyPress = true; // 阻止系统提示音
                }
            };

            InitContextMenuStrip();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            m_connection = new ConnectionDatabase_S2("Server=172.18.80.59;Port=5432;Database=ag_cim;Uid=agcim;Pwd=ce92481d8945;", "PG");
            InitComboBoxAuthor();
            QueryAll();
            this.dateTimePicker_start.ValueChanged += dateTimePicker_ValueChanged;
            this.dateTimePicker_end.ValueChanged += dateTimePicker_ValueChanged;
        }

        private void CheckUpdate()
        {
            AutoUpdater.Mandatory = true;//强制更新
            AutoUpdater.Start("\\\\192.168.2.57/agcimDesktopFiles/installationPackage/AgCIM技术日志编写软件/AutoUpdater.xml");
        }

        /// <summary>
        /// 添加右键菜单
        /// </summary>
        private void InitContextMenuStrip()
        {
            // 创建右键菜单
            ToolStripMenuItem editMenuItem = new ToolStripMenuItem("编辑");
            editMenuItem.Click += (s, e) =>
            {
                // 获取鼠标右键点击位置的行
                Point mousePosition = dataGridView1.PointToClient(((ContextMenuStrip)((ToolStripMenuItem)s).Owner).Location);
                DataGridView.HitTestInfo hitTest = dataGridView1.HitTest(mousePosition.X, mousePosition.Y);
                if (hitTest.RowIndex >= 0)
                {
                    EditDailyLogByRowIndex(hitTest.RowIndex);
                }
            };
            ToolStripMenuItem viewMenuItem = new ToolStripMenuItem("查看");
            viewMenuItem.Click += (s, e) =>
            {
                // 获取鼠标右键点击位置的行
                Point mousePosition = dataGridView1.PointToClient(((ContextMenuStrip)((ToolStripMenuItem)s).Owner).Location);
                DataGridView.HitTestInfo hitTest = dataGridView1.HitTest(mousePosition.X, mousePosition.Y);
                if (hitTest.RowIndex >= 0)
                {
                    ViewDailyLogByRowIndex(hitTest.RowIndex);
                }
            };
            ToolStripMenuItem view3DaysMenuItem = new ToolStripMenuItem("查看三天内日志");
            view3DaysMenuItem.Click += (s, e) =>
            {
                // 获取鼠标右键点击位置的行
                Point mousePosition = dataGridView1.PointToClient(((ContextMenuStrip)((ToolStripMenuItem)s).Owner).Location);
                DataGridView.HitTestInfo hitTest = dataGridView1.HitTest(mousePosition.X, mousePosition.Y);
                if (hitTest.RowIndex >= 0)
                {
                    string author = dataGridView1.Rows[hitTest.RowIndex].Cells[0].Value.ToString();
                    string logDate = dataGridView1.Rows[hitTest.RowIndex].Cells[1].Value.ToString();
                    DateTime selectedDate = DateTime.Parse(logDate);

                    // 计算日期范围
                    string startDate = selectedDate.AddDays(-2).ToString("yyyy-MM-dd");
                    string endDate = selectedDate.ToString("yyyy-MM-dd");

                    // 查询三天内的日志
                    string sql = $@"SELECT author, logdate, content 
                        FROM {m_tableName} 
                        WHERE author = '{author}'
                        AND logdate >= '{startDate}' 
                        AND logdate <= '{endDate}'
                        ORDER BY logdate ASC";

                    DataTable result = m_connection.SelectData(sql);

                    if (result.Rows.Count == 0)
                    {
                        MessageBox.Show("没有找到三天内的日志记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    // 调用OpenDailyLogForm显示三天内的日志
                    OpenDailyLogForm(author, logDate, TextUtils.BuildContentForRows(result.Rows), false, false);
                }
            };

            ToolStripMenuItem viewWeekMenuItem = new ToolStripMenuItem("查看本周日志");
            viewWeekMenuItem.Click += (s, e) =>
            {
                // 获取鼠标右键点击位置的行
                Point mousePosition = dataGridView1.PointToClient(((ContextMenuStrip)((ToolStripMenuItem)s).Owner).Location);
                DataGridView.HitTestInfo hitTest = dataGridView1.HitTest(mousePosition.X, mousePosition.Y);
                if (hitTest.RowIndex >= 0)
                {
                    string author = dataGridView1.Rows[hitTest.RowIndex].Cells[0].Value.ToString();
                    string logDate = dataGridView1.Rows[hitTest.RowIndex].Cells[1].Value.ToString();
                    DateTime selectedDate = DateTime.Parse(logDate);

                    // 计算本周的起止日期
                    DayOfWeek dayOfWeek = selectedDate.DayOfWeek;
                    int daysToMonday = dayOfWeek == DayOfWeek.Sunday ? 6 : (int)dayOfWeek - 1;
                    DateTime monday = selectedDate.AddDays(-daysToMonday);
                    DateTime sunday = monday.AddDays(6);

                    // 查询本周的日志
                    string sql = $@"SELECT author, logdate, content 
                        FROM {m_tableName} 
                        WHERE author = '{author}'
                        AND logdate >= '{monday:yyyy-MM-dd}' 
                        AND logdate <= '{sunday:yyyy-MM-dd}'
                        ORDER BY logdate ASC";

                    DataTable result = m_connection.SelectData(sql);

                    if (result.Rows.Count == 0)
                    {
                        MessageBox.Show("没有找到本周的日志记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }

                    // 调用OpenDailyLogForm显示本周的日志
                    OpenDailyLogForm(author, logDate, TextUtils.BuildContentForRows(result.Rows), false, false);
                }
            };


            ToolStripMenuItem refreshMenuItem = new ToolStripMenuItem("刷新");
            refreshMenuItem.Click += (s, e) => { QuerySomeDays(); };

            ContextMenuStrip contextMenuStrip = new ContextMenuStrip();
            contextMenuStrip.Items.Add(viewMenuItem);
            contextMenuStrip.Items.Add(view3DaysMenuItem);
            contextMenuStrip.Items.Add(viewWeekMenuItem);
            contextMenuStrip.Items.Add(new ToolStripSeparator());// 添加分割线
            contextMenuStrip.Items.Add(editMenuItem);
            contextMenuStrip.Items.Add(new ToolStripSeparator());// 添加分割线
            contextMenuStrip.Items.Add(refreshMenuItem);

            // 为dataGridView1设置右键菜单
            this.dataGridView1.ContextMenuStrip = contextMenuStrip;
        }

        private void InitComboBoxAuthor()
        {
            UpdateComboBoxItems();
            //添加事件
            this.comboBox_author.SelectedIndexChanged += comboBox_author_SelectedIndexChanged;
        }
        private void UpdateComboBoxItems()
        {
            //记录已选中的文本
            string selectedText = this.comboBox_author.Text;

            //清空
            this.comboBox_author.Items.Clear();

            // 查询所有作者姓名并去重
            string authorSql = $@"SELECT DISTINCT author 
                FROM {m_tableName} 
                ORDER BY author ASC";
            // 添加"全部"选项
            this.comboBox_author.Items.Add("---全部---");
            DataTable authors = m_connection.SelectData(authorSql);
            // 将查询到的作者姓名添加到下拉框
            foreach (DataRow row in authors.Rows)
            {
                string authorName = row["author"].ToString();
                if (!string.IsNullOrEmpty(authorName))
                {
                    this.comboBox_author.Items.Add(authorName);
                }
            }

            // 如果之前有选中的文本，则重新选择该文本
            if (!string.IsNullOrEmpty(selectedText))
            {
                // 遍历ComboBox项查找匹配的文本
                for (int i = 0; i < this.comboBox_author.Items.Count; i++)
                {
                    if (this.comboBox_author.Items[i].ToString() == selectedText)
                    {
                        this.comboBox_author.SelectedIndex = i;
                        break;
                    }
                }
            }
            // 如果没有选中的文本，则默认选择"全部"
            else
            {
                this.comboBox_author.SelectedIndex = 0;
            }
        }
        private void dataGridView1_CellPainting(object? sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.ColumnIndex == 3 && e.RowIndex >= 0)
            {
                e.PaintBackground(e.CellBounds, true);
                Rectangle rect1 = new Rectangle(e.CellBounds.X, e.CellBounds.Y, e.CellBounds.Width / 2, e.CellBounds.Height);
                Rectangle rect2 = new Rectangle(e.CellBounds.X + rect1.Width, e.CellBounds.Y, rect1.Width, e.CellBounds.Height);
                ControlPaint.DrawButton(e.Graphics, rect1, ButtonState.Normal);
                ControlPaint.DrawButton(e.Graphics, rect2, ButtonState.Normal);
                // 计算文本绘制位置使其居中显示
                SizeF size1 = e.Graphics.MeasureString("编辑", this.Font);
                SizeF size2 = e.Graphics.MeasureString("查看", this.Font);
                float x1 = rect1.X + (rect1.Width - size1.Width) / 2;
                float y1 = rect1.Y + (rect1.Height - size1.Height) / 2;
                float x2 = rect2.X + (rect2.Width - size2.Width) / 2;
                float y2 = rect2.Y + (rect2.Height - size2.Height) / 2;
                e.Graphics.DrawString("编辑", this.Font, Brushes.Black, x1, y1);
                e.Graphics.DrawString("查看", this.Font, Brushes.Black, x2, y2);
                e.Handled = true;  // 阻止默认绘制
            }
        }
        private void dataGridView1_CellMouseClick(object? sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex == 3 && e.RowIndex >= 0)
            {
                Rectangle cellRect = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false);
                Rectangle btn1Rect = new Rectangle(cellRect.X, cellRect.Y, cellRect.Width / 2, cellRect.Height);
                Point absoluteLocation = new Point(e.Location.X + cellRect.X, e.Location.Y + cellRect.Y);
                if (btn1Rect.Contains(absoluteLocation))
                {
                    // 处理第一个按钮点击
                    EditDailyLogByRowIndex(e.RowIndex);
                }
                Rectangle btn2Rect = new Rectangle(cellRect.X + cellRect.Width / 2, cellRect.Y, cellRect.Width / 2, cellRect.Height);
                if (btn2Rect.Contains(absoluteLocation))
                {
                    // 处理第二个按钮点击
                    ViewDailyLogByRowIndex(e.RowIndex);
                }
            }
        }
        private void dataGridView1_CellDoubleClick(object? sender, DataGridViewCellEventArgs e)
        {
            // 仅内容列触发
            if (e.ColumnIndex == 2 && e.RowIndex >= 0)
            {
                ViewDailyLogByRowIndex(e.RowIndex);
            }
        }
        private void button_addLog_Click(object sender, EventArgs e)
        {
            AddNewDailyLog();
        }
        private void button_showAllDate_Click(object sender, EventArgs e)
        {
            QueryAll();
        }
        private void button_exportDailyLog_Click(object sender, EventArgs e)
        {
            // 弹出保存文件对话框
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "HTML文件|*.html";
            saveFileDialog.Title = "保存日志文件";
            saveFileDialog.DefaultExt = "html";

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    // 构建SQL查询条件
                    string authorCondition = "";
                    if (comboBox_author.SelectedItem.ToString() != "---全部---")
                    {
                        authorCondition = $" AND author = '{comboBox_author.SelectedItem}'";
                    }

                    string startDate = dateTimePicker_start.Value.ToString("yyyy-MM-dd");
                    string endDate = dateTimePicker_end.Value.ToString("yyyy-MM-dd");
                    string dateBetween = $" WHERE logdate >= '{startDate}' AND logdate <= '{endDate}'";

                    // 查询数据库
                    string sql = $@"SELECT author, logdate, content 
                        FROM {m_tableName} 
                        {(authorCondition == "" ? dateBetween : dateBetween + authorCondition)}
                        ORDER BY logdate ASC, author ASC";

                    DataTable result = m_connection.SelectData(sql);

                    // 构建HTML内容
                    StringBuilder htmlBuilder = new StringBuilder();
                    htmlBuilder.AppendLine("<!DOCTYPE html>");
                    htmlBuilder.AppendLine("<html>");
                    htmlBuilder.AppendLine("<head>");
                    htmlBuilder.AppendLine("<meta charset='utf-8'>");
                    htmlBuilder.AppendLine("<title>日志导出</title>");
                    htmlBuilder.AppendLine("<style>");
                    htmlBuilder.AppendLine("body { font-family: Arial, sans-serif; margin: 20px; }");
                    htmlBuilder.AppendLine(".log-divider { margin-bottom: 20px; border-bottom: 1px solid #ccc; padding-bottom: 10px; }");
                    htmlBuilder.AppendLine(".log-header { color: #2c5282; font-size: 1.2em; margin-bottom: 12px; font-family: 'Microsoft YaHei', sans-serif; font-weight: 700; text-shadow: 1px 1px 2px rgba(44, 82, 130, 0.1); }");
                    htmlBuilder.AppendLine("</style>");
                    htmlBuilder.AppendLine("</head>");
                    htmlBuilder.AppendLine("<body>");

                    // 检查是否有数据需要导出
                    if (result.Rows.Count == 0)
                    {
                        MessageBox.Show("没有找到需要导出的日志！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    foreach (DataRow row in result.Rows)
                    {
                        string author = row["author"].ToString();
                        string logDate = Convert.ToDateTime(row["logdate"]).ToString("yyyy-MM-dd");
                        string content = row["content"].ToString();

                        htmlBuilder.AppendLine("<div class='log-divider'>");
                        htmlBuilder.AppendLine($"<div class='log-header'>作者：{author} | 日期：{logDate}</div>");
                        htmlBuilder.AppendLine($"<div class='log-content'>{content}</div>");
                        htmlBuilder.AppendLine("</div>");
                    }

                    htmlBuilder.AppendLine("</body>");
                    htmlBuilder.AppendLine("</html>");

                    // 保存文件
                    File.WriteAllText(saveFileDialog.FileName, htmlBuilder.ToString(), System.Text.Encoding.UTF8);
                    MessageBox.Show("导出成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"导出失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        private void button_search_Click(object sender, EventArgs e)
        {
            QuerySomeDays();
        }
        private void dateTimePicker_ValueChanged(object? sender, EventArgs e)
        {
            QuerySomeDays();
        }
        private void comboBox_author_SelectedIndexChanged(object? sender, EventArgs e)
        {
            QuerySomeDays();
        }
        private void QueryAll()
        {
            // 查询最早的日志日期
            string earliestDateSql = $@"SELECT MIN(logdate) as earliest_date 
                FROM {m_tableName}";
            DataTable dateResult = m_connection.SelectData(earliestDateSql);

            if (dateResult.Rows.Count > 0 && dateResult.Rows[0]["earliest_date"] != DBNull.Value)
            {
                // 设置开始日期为最早的日志日期
                dateTimePicker_start.Value = Convert.ToDateTime(dateResult.Rows[0]["earliest_date"]);
            }
            else
            {
                // 如果没有数据，设置为当前日期
                dateTimePicker_start.Value = DateTime.Today;
            }

            // 查询指定日期范围内的日志
            QuerySomeDays();
        }
        private void QuerySomeDays()
        {
            // 获取选中的开始和结束日期
            string startDate = dateTimePicker_start.Value.ToString("yyyy-MM-dd");
            string endDate = dateTimePicker_end.Value.ToString("yyyy-MM-dd");

            // 获取作者筛选条件
            string authorCondition = this.comboBox_author.SelectedItem.ToString() != "---全部---"
                ? $"AND author = '{comboBox_author.SelectedItem}'"
                : "";

            string searchCondition = !string.IsNullOrEmpty(textBox_search.Text)
                ? $"AND summary LIKE '%{textBox_search.Text}%'"
                : "";

            string sql = $@"SELECT author, logdate, summary 
                FROM {m_tableName} 
                WHERE logdate >= '{startDate}' AND logdate <= '{endDate}'
                {authorCondition}
                {searchCondition}
                ORDER BY logdate DESC, author ASC";

            // 执行查询
            DataTable result = m_connection.SelectData(sql);

            // 清空现有数据
            dataGridView1.Rows.Clear();

            // 将查询结果写入DataGridView
            foreach (DataRow row in result.Rows)
            {
                int rowIndex = dataGridView1.Rows.Add();
                dataGridView1.Rows[rowIndex].Cells[0].Value = row["author"].ToString();
                dataGridView1.Rows[rowIndex].Cells[1].Value = Convert.ToDateTime(row["logdate"]).ToString("yyyy-MM-dd");
                dataGridView1.Rows[rowIndex].Cells[2].Value = row["summary"].ToString();
            }
        }
        private string GetContent(string name, string logDate)
        {
            string sql = $@"SELECT content 
                FROM {m_tableName} 
                WHERE author = '{name}' 
                AND logdate = '{logDate}'
                ORDER BY createtime DESC
                LIMIT 1";

            var result = m_connection.SelectData(sql);
            return result.Rows.Count == 0 ? string.Empty : result.Rows[0]["content"].ToString();
        }

        private void AddNewDailyLog()
        {
            OpenDailyLogForm(string.Empty, string.Empty, string.Empty, true, true);
        }
        private void EditDailyLog(string author, string date, string content)
        {
            OpenDailyLogForm(author, date, content, false, true);
        }
        private void ViewDailyLog(string author, string date, string content)
        {
            OpenDailyLogForm(author, date, content, false, false);
        }
        private void EditDailyLogByRowIndex(int rowIndex)
        {
            string author = dataGridView1.Rows[rowIndex].Cells[0].Value.ToString();
            string logDate = dataGridView1.Rows[rowIndex].Cells[1].Value.ToString();
            string content = GetContent(author, logDate);
            if (string.IsNullOrEmpty(content))
            {
                MessageBox.Show("不存在数据");
                return;
            }
            EditDailyLog(author, logDate, content);
        }
        private void ViewDailyLogByRowIndex(int rowIndex)
        {
            string author = dataGridView1.Rows[rowIndex].Cells[0].Value.ToString();
            string logDate = dataGridView1.Rows[rowIndex].Cells[1].Value.ToString();
            string content = GetContent(author, logDate);
            if (string.IsNullOrEmpty(content))
            {
                MessageBox.Show("不存在数据");
                return;
            }
            ViewDailyLog(author, logDate, content);
        }

        private Form m_editForm { get; set; }
        private void OpenDailyLogForm(string author, string date, string content, bool allowEditAuthorAndDate, bool allowEditContent)
        {
            // 创建新的日志编辑窗体
            m_editForm = new Form();
            m_editForm.Text = "日志";
            m_editForm.Size = new Size(1280, 960);

            // 创建WebView2控件
            WebView2 webView = new WebView2();
            webView.Dock = DockStyle.Fill;
            m_editForm.Controls.Add(webView);

            // 获取HTML文件的路径
            string htmlPath = Path.Combine(Application.StartupPath, "Resources", "cimPaperEditor.html");

            try
            {
                webView.CoreWebView2InitializationCompleted += (sender, e) =>
                {
                    if (e.IsSuccess)
                    {
                        webView.CoreWebView2.WebMessageReceived += CoreWebView2_WebMessageReceived;
                    }
                    else
                    {
                        MessageBox.Show($"初始化失败");
                    }
                };
                webView.NavigationCompleted += (s, navE) =>
                {
                    if (navE.IsSuccess && !string.IsNullOrEmpty(content))
                    {
                        if (!string.IsNullOrEmpty(content))
                        {
                            string script = $"window.quill.clipboard.dangerouslyPasteHTML('{content}');"
                            //string script = $"window.quill.root.innerHTML='{content}';"
                            + $"window.document.getElementById('author').value='{author}';"
                            + $"window.document.getElementById('dailyLogDate').value='{date}';";
                            webView.CoreWebView2.ExecuteScriptAsync(script);
                        }
                        if (!allowEditAuthorAndDate)
                        {
                            string script = "window.document.getElementById('author').readOnly=true;"//禁用作者姓名编辑
                            + "window.document.getElementById('dailyLogDate').readOnly=true;";//禁用日期编辑
                            webView.CoreWebView2.ExecuteScriptAsync(script);
                        }
                        if (!allowEditContent)
                        {
                            string script = "window.quill.enable(false);"//禁用文本框编辑
                            + "window.quill.getModule('toolbar').container.hidden=true;"//隐藏工具栏
                            + "window.document.getElementById('saveButton').hidden=true;";//隐藏保存按钮
                            webView.CoreWebView2.ExecuteScriptAsync(script);
                        }
                    }
                };

                // 初始化WebView2并加载HTML
                webView.EnsureCoreWebView2Async().ContinueWith(t =>
                {
                    if (t.IsCompleted)
                    {
                        m_editForm.Invoke(new Action(() =>
                        {
                            webView.CoreWebView2.Navigate(htmlPath);
                        }));
                    }
                });

                // 显示窗体
                m_editForm.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载编辑器失败：" + ex.Message);
            }
        }
        private void CoreWebView2_WebMessageReceived(object? sender, CoreWebView2WebMessageReceivedEventArgs e)
        {
            string message = string.Copy(e.WebMessageAsJson);
            if (!string.IsNullOrEmpty(message))
            {
                Dictionary<string, object> dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(message);
                if (dict != null && dict.Count > 0)
                {
                    Reflex(dict);
                }
            }
        }
        private void Reflex(Dictionary<string, object> dict)
        {
            Type currentType = this.GetType();
            string method = $"{dict["method"]}";
            MethodInfo methodInfo = currentType.GetMethod(method, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Default);
            if (methodInfo != null)
            {
                methodInfo.Invoke(this, new object[] { dict });
            }
            else
            {
                Console.WriteLine($"未找到名为 {method} 的方法。");
            }
        }
        private async void UploadToDB(Dictionary<string, object> dict)
        {
            try
            {
                string author = dict["author"].ToString();
                string content = dict["content"].ToString();
                string summary = TextUtils.GetSummaryFromHtml(content);
                string sql = $@"INSERT INTO {m_tableName} (author, logdate, content, summary, createtime) 
                        VALUES ('{author}',
                                '{dict["date"]}', 
                                '{content}', 
                                '{summary}',
                                '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}')
                        ON CONFLICT ON CONSTRAINT primary_author_logdate  -- 引用约束名
                        DO UPDATE SET 
                            content = EXCLUDED.content,
                            summary = EXCLUDED.summary";

                m_connection.ExecuteSQL(sql);

                MessageBox.Show("保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                //刷新下拉框，comboBox的事件会触发刷新表格事件
                UpdateComboBoxItems();

                m_editForm.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #region 5-1 产品时序图
        private void button1_Click(object sender, EventArgs e)
        {
            // 创建新的日志编辑窗体
            var productMap = new Form();
            productMap.Text = "产品时序";
            productMap.Size = new Size(1280, 960);

            // 创建WebView2控件
            WebView2 webView = new WebView2();
            webView.Dock = DockStyle.Fill;
            productMap.Controls.Add(webView);

            // 获取HTML文件的路径
            string htmlPath = Path.Combine(Application.StartupPath, "Resources", "yuanbao_html_20250820_aryDZs.html");

            try
            {
                webView.Source = new Uri("http://183.6.116.73:1013/AgCIM%E6%8A%80%E6%9C%AF%E6%9C%88%E5%88%8A/jikepages/%E8%BD%AF%E4%BB%B6%E9%83%A8%E7%BD%B2/Windows%E7%8E%AF%E5%A2%83/yuanbao_html_20250820_aryDZs.html");
                // 显示窗体
                productMap.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载编辑器失败：" + ex.Message);
            }
        } 
        #endregion
    }
}
